package org.arch_learn.servlet_container.components.connector.adapters;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.arch_learn.servlet_container.components.Service;
import org.arch_learn.servlet_container.pojo.CustomHttpServletResponse;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class ServletResponseAdapter {

    public static FullHttpResponse adaptHttpServletResponseToNetty(CustomHttpServletResponse httpServletResponse, FullHttpResponse defaultFullHttpResponse) {
        String messageText = httpServletResponse.getMessageText();
        ByteBuf byteBuf = Unpooled.copiedBuffer(messageText, CharsetUtil.UTF_8);
        defaultFullHttpResponse = defaultFullHttpResponse.replace(byteBuf);
        HttpHeaders headers = defaultFullHttpResponse.headers();
        headers.set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8")
                .set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
        return defaultFullHttpResponse;
    }

    public static RandomAccessFile getNettyReadFileResponse(Service service, HttpRequest nettyHttpRequest, FullHttpResponse fullHttpResponse) throws IOException {
        String uri = nettyHttpRequest.uri();
        String appBase = service.getEngine()
                .getHosts().values().stream()
                .findFirst().get().getAppBase();
        String filePath = appBase + uri;
        RandomAccessFile randomAccessFile = new RandomAccessFile(new File(filePath), "r");
        long length = randomAccessFile.length();
        DefaultFullHttpResponse defaultFullHttpResponse = (DefaultFullHttpResponse) fullHttpResponse;
        HttpHeaders headers = defaultFullHttpResponse.headers();
        headers.set(HttpHeaderNames.CONTENT_LENGTH, length)
                .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        //动态地根据文件名获取文件类型
        MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
        headers.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(filePath));
        return randomAccessFile;
    }
}
